package com.dorukdestan.p2pshare.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;

import com.dorukdestan.p2pshare.logger.Logger;

public class Crc32Generator {
	
	private static CRC32 crc;
	private static Logger logger;
	
	static{
		logger = new Logger(Crc32Generator.class);
	}
	
	public synchronized static long generateCrc(String filePath){
		File file = new File(filePath);
		return generateCrc(file);
	}
	
	public synchronized static long generateCrc(File file){
	InputStream is = null;
	crc = new CRC32();

	logger.debug("Hashing... " + file.getName());
	
	try {
		is =  new FileInputStream(file);
		
	    byte[] buffer = new byte[1024];

	    int numRead;
		do {
			numRead = is.read(buffer);
			if (numRead > 0) {
				crc.update(buffer, 0, numRead);
			}
		} while (numRead != -1);
		
		return crc.getValue();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		if(is != null)
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	return -1;
	}
}
